# !/usr/bin/python
# coding:utf-8
import json
import xlwt
import logging
import os
import time


def run():
    ret = []
    for host in os.listdir("../output"):
        if os.path.isdir("../output/%s" % host):
            logFile = "../output/%s/rpm.log" % host
            hostInfo = {}
            with open(logFile, "r", encoding="utf-8") as f:
                for index, line in enumerate(f.readlines()):
                    line = line.replace("\n", "")
                    print(index)
                    if index == 0:
                        # 主机名
                        hostInfo["hostname"] = line
                    if index == 1:
                        # 系统版本
                        hostInfo["release"] = line
                    if index == 2:
                        # 内核
                        hostInfo["uname"] = line
                    if index == 3:
                        # 内核
                        hostInfo["ip"] = line

                    line = line.split(" ")
                    if "openssh" == line[0]:
                        hostInfo["rpm"] = line[0]
                        hostInfo["rpm_version"] = line[1]
                        hostInfo["rpm_release"] = line[2]
                        hostInfo["rpm_arch"] = line[3]

            ret.append(hostInfo)

    create_excel(ret)


def create_excel(data_list):
    with open("../conf/config.json", "r", encoding="utf-8") as f:
        config = json.loads(f.read())

        today = time.strftime("%Y%m%d%H%M", time.localtime())
        excel_name = "{}_{}.xls".format(config["filename"], today)
        save_name = "{}/{}_{}.xls".format(config["output"], config["filename"], today)
        # 自动创建路径
        if os.path.exists(config["output"]) is False:
            os.makedirs(config["output"])

        logging.info("{}报告生成中....".format(excel_name))

        report = xlwt.Workbook(encoding='utf-8')
        sheet = report.add_sheet("sheet1")

        # 创建表头和列宽
        for x, column in enumerate(config["columns"]):
            sheet.write(0, x, column["title"])
            sheet.col(x).width = 256 * column["width"]

        # 写入数据
        for x, row_data in enumerate(data_list):
            x = x + 1
            for y, column in enumerate(config["columns"]):
                if config["columns"][y]["key"] == 'index':
                    cell_value = x
                else:
                    cell_value = row_data[config["columns"][y]["key"]]
                if "color" in config["columns"][y]:
                    if cell_value in config["columns"][y]["color"]:
                        cell_style = xlwt.XFStyle()
                        pattern = xlwt.Pattern()
                        pattern.pattern = xlwt.Pattern.SOLID_PATTERN
                        pattern.pattern_fore_colour = xlwt.Style.colour_map[config["columns"][y]["color"][cell_value]]
                        cell_style.pattern = pattern
                        sheet.write(x, y, cell_value, cell_style)
                    else:
                        sheet.write(x, y, cell_value)
                else:
                    sheet.write(x, y, cell_value)

        report.save(save_name)

        logging.info("报告已生成，保存路径{}".format(excel_name, save_name))


if __name__ == "__main__":
    run()
